package org.xx.armory.io;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class ClassPathURLConnection
        extends URLConnection {
    private URL resource;

    /**
     * Constructs a URL connection to the specified URL. A connection to
     * the object referenced by the URL is not created.
     *
     * @param url
     *         the specified URL.
     */
    protected ClassPathURLConnection(
            URL url
    ) {
        super(url);

        this.resource = null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void connect()
            throws IOException {
        String path = getURL().getPath();
        if (path == null || path.isEmpty()) {
            throw new IOException("path cannot be null or empty");
        }

        path = "/" + path;
        resource = getClass().getClassLoader().getResource(path);
        if (resource == null) {
            throw new IOException("cannot find resource: " + path);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public InputStream getInputStream()
            throws IOException {
        if (this.resource == null) {
            throw new IOException("cannot open null resource");
        }

        return this.resource.openStream();
    }
}
